package DB;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.*;

public class DBConnector{
	public static String freeBaseImageURL="http://img.freebase.com/api/trans/image_thumb";
	
	static protected Connection openConnection(){
		Connection conn=null;
		try{
			Class.forName("com.mysql.jdbc.Driver");
		}
		catch (ClassNotFoundException e){
			System.out.println("Unable to load the MySQL JDBC driver..");
			java.lang.System.exit(0); 
		}
		//System.out.println("Driver loaded successfully");
		//System.out.print("Trying to connect.. ");
		try{
			//conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbgame","root","123");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3305/DbMysql04","DbMysql04","DbMysql04");
			//conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbmysql04","root","ilana1");
		}
		catch (SQLException e){
			System.out.println("Unable to connect - " + e.toString());
			java.lang.System.exit(0); 
		}
		//System.out.println("Connected!");
		return conn;
	}
	
	static protected void closeConnection(Connection conn){
		try{
			conn.close();
		}
		catch (SQLException e){
			System.out.println("Unable to close the connection - " + e.toString());
			java.lang.System.exit(0); 
		}	
	}
	
	static public InputStream getInputStreamOfPicture(String freeBaseID){
		URL url;
		try {
			url = new URL("https://api.freebase.com/api/trans/image_thumb"+freeBaseID);
			HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
			myConnection.setRequestMethod("GET");
			myConnection.connect();
			int answer = myConnection.getResponseCode();
			if (answer == HttpURLConnection.HTTP_OK)//URL is OK
				return myConnection.getInputStream();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
		}
	return null;
	}
	
	static public void setChanged(int id,String tablename){
		Connection conn= openConnection();
		try {
			Statement stmt = conn.createStatement();
			stmt.executeUpdate("UPDATE "+tablename+" SET `changed`=1 WHERE `id`=" + String.valueOf(id));
			
			
		} catch (SQLException e) {
		System.out.println("SQL error at setChanged"+e.getMessage());
		}	
	}
	
	static public String getfreeBaseID(int id,String table){
		Connection conn= openConnection();
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT freeBaseID FROM "+table+" WHERE id=" + String.valueOf(id));
			rs.next();
			return rs.getString("freeBaseID");
		} catch (SQLException e) {
		System.out.println("SQL error "+e.getMessage());
		}
		return null;
	}
}